/******************
人员类考核
* */
<template>
  <el-dialog
    :title="dialogTitle"
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="80%"
    top="8vh"
    @close="closeDialog()"
  >
    <el-form
      ref="dataForm"
      :rules="formRules"
      :model="dataForm"
      label-position="right"
      label-width="120px"
      @keyup.enter.native="dataFormSubmit()"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="周期名称" style="width:60%">
            <span>{{fatherData.period}}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="考核时间" style="width:60%">
            <span>{{fatherData.assessBeginTime?fatherData.assessBeginTime.slice(0,10):""}}--{{fatherData.assessEndTime?fatherData.assessEndTime.slice(0,10):''}}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="考核名称" prop="name" style="width:60%">
            <el-input v-model="dataForm.name" :disabled="dataForm.id!==undefined"></el-input>
          </el-form-item>
        </el-col>
        <!--news 2022/4/8 -->
        <el-col :span="12">
          <el-form-item label="模板名称:" prop="templateId" style="width:60%">
            <el-select
              v-model="dataForm.templateId"
              placeholder="请选择模板"
              class="xiaLa"
              style="width: 100%"
              :clearable="true"
              @change="selecteRefresh"
            >
              <el-option
                v-for="(item, index) in templateNamesList"
                :key="index"
                :label="item.name"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="被考核人" prop="ids" v-if="dialogTitle=='新增人员考核'">
            <el-button icon="el-icon-user-solid" @click="showPerson" type="text"></el-button>
            <span v-for="it in options" :key="it.userId">
              <el-tooltip
                class="item"
                :disabled="options.length < 3"
                effect="dark"
                :content="shaiXuan(options, '被考核人')"
                placement="top-start"
              >
                <span style="font-size: 16px; color: #303745">{{ it.userName }}、</span>
              </el-tooltip>
            </span>
          </el-form-item>
          <el-form-item label="被考核人" v-else>
            <span v-for="it in options" :key="it.userId">
              <el-tooltip
                class="item"
                :disabled="options.length < 3"
                effect="dark"
                :content="shaiXuan(options, '被考核人')"
                placement="top-start"
              >
                <span style="font-size: 16px; color: #303745">{{ it.userName }}、</span>
              </el-tooltip>
            </span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div style="height: 10px; border-top: 1px solid #b0bde2"></div>
    <div class="tabBox">
      <div class="btnBox">
        <div>
          <el-tooltip effect="dark" content="选择指标" placement="top">
            <el-button icon="el-icon-plus" type="success" circle @click="showTarLibrary"></el-button>
          </el-tooltip>
          <el-button
            @click="deleteIndex"
            :disabled="canDelete"
            type="danger"
            icon="el-icon-delete"
            circle
          ></el-button>
        </div>
        <div>
          <el-button @click="repeatTarget" type="primary">复用指标</el-button>
        </div>
      </div>
    </div>
    <el-row>

      <el-table
        style="width: 100%;margin-top:20px"
        :data="dataList"
        border
        :row-class-name="tableRowClassName"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="type" align="center" label="指标类别"></el-table-column>
        <el-table-column prop="name" align="center" label="指标名称" show-overflow-tooltip></el-table-column>
        <el-table-column prop="weight" align="center" label="权重(%)">
          <template slot-scope="scope">
            <el-form :model="scope.row" :rules="rules">
               <el-form-item prop="weight">
                  <el-input
                    oninput="value=value.replace(/[^\d.]/g, '').replace(/^\./g, '').replace(/\.{2,}/g, '.').replace(/(\.\d+)\./g, '$1').replace(/^0+(\d)/, '$1').replace(/(\d{15})\d*/, '$1').replace(/(\.\d{2})\d*/, '$1')"
                    v-model="scope.row.weight"
                  ></el-input>
               </el-form-item>
            </el-form>
           <!-- <el-input v-model.number="scope.row.weight"
            @blur="checkIsNum(scope.row,scope.$index)"></el-input>-->
          </template>
        </el-table-column>
        <el-table-column prop="formula" align="center" label="计算公式"  show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{scope.row.formula}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="targetValue" align="center" label="目标值" min-width="120">
          <template slot-scope="scope">
            <span>
              <el-input
                :rows="1"
                type="textarea"
                v-model="scope.row.targetValue"
              ></el-input>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="unit" align="center" label="单位" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{scope.row.unit}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="completeValue" align="center" label="完成值获取方式" width="150">
            <template slot-scope="scope">
              <el-select
                @change="$set(scope.row, scope.row.completeValue, $event)"
                :clearable="true"
                v-model="scope.row.completeValue"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in dataFromList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                ></el-option>
              </el-select>
            </template>
        </el-table-column>
        <el-table-column
          prop="provideRealName"
          align="center"
          label="数据提供部门/人"
          show-overflow-tooltip
          width="200"
        >
          <template slot-scope="scope">
            <span
              v-if="scope.row.isLiaison==0"
              style="color:blue"
              @click="showDataProvide(scope.row,scope.$index)"
            >
              {{scope.row.provideRealName}}
              <i class="el-icon-edit-outline"></i>
            </span>
            <span v-else style="color:blue" @click="showDataProvide(scope.row,scope.$index)">
              {{scope.row.provideDeptName}}
              <i class="el-icon-edit-outline"></i>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="normRule" align="center" label="指标规则" show-overflow-tooltip></el-table-column>
        <!--<el-table-column prop="itemIndex" align="center" width="80" label="排序号"></el-table-column>-->
      </el-table>

    </el-row>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" v-if="dialogTitle=='新增人员考核'" plain @click="handleConfirm">确定</el-button>
      <el-button type="primary" v-if="isEdit&&dialogTitle=='编辑'" plain @click="handleConfirm">确定</el-button>
      <el-button type="primary" plain @click="closeDialog()">返回</el-button>
    </span>
    <UserCommonSelect v-if="usercomment" ref="usercomment" @submitfy="submitfy"></UserCommonSelect>
    <FormulateDialog v-if="formulateDialog" ref="formulateDialog" @submitfy="submitfy1"></FormulateDialog>
    <!-- 考核指标库 -->
    <el-dialog title="精准激励指标库" :visible.sync="dialogVisible" width="80%" append-to-body>
      <zhibiaoTable ref="zhibiaoRef" @func="getRow"></zhibiaoTable>
      <span slot="footer" class="dialog-footer">
        <el-button plain type="primary" @click="addZhibiao">添 加</el-button>
        <el-button plain @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 复用指标 -->
    <el-dialog title="请选择指标" :visible.sync="repeatVisible" width="80%" append-to-body>
      <el-form :inline="true" ref="form" :model="searchForm" label-width="120px">
        <el-row>
          <el-col :span="5">
            <el-form-item label="考核名称">
              <el-input @change="getDataList" v-model="searchForm.name" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="考核对象">
              <el-input @change="getDataList" v-model="searchForm.assessRealName" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item>
              <el-button @click="handleSearch" type="primary">搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-table
        style="width: 100%;margin-top:20px"
        :data="repeatTargetList"
        border
        stripe
        ref="multipleTable"
        @select-all="onSelectAll"
        header-align="center"
        @selection-change="handleRepeatChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="assessRealName" align="center" label="考核对象" width="140"></el-table-column>
        <el-table-column prop="name" align="center" label="考核名称" show-overflow-tooltip></el-table-column>
        <el-table-column prop="period" align="center" label="考核周期" show-overflow-tooltip></el-table-column>
        <el-table-column prop="weight" align="center" label="权重" show-overflow-tooltip>
          <template slot-scope="scope">
            <span :class="scope.row.weight==100?'weightColor':'weightRed'">{{scope.row.weight}}</span>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <div class="avue-crud__pagination">
        <el-pagination
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
          :current-page="pageData.pageIndex"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageData.pageSize"
          :total="pageData.totalPage"
          background
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button plain type="primary" @click="addRepeatIndex">添 加</el-button>
        <el-button plain @click="repeatVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </el-dialog>
</template>

<script>
import UserCommonSelect from "@/views/dailyExamine/components/usercomment-selectCopy-zb"; //人员选择的组件
import zhibiaoTable from "@/views/dailyExamine/components/targetIndexTable"; //指标表格
import {
  examineList,
  addExamin,
  editExamin,
  getMbnameSelect,
  zltest,
  checkitem
} from "@/api/dailyExamine/targetExamine/createAssessment";
import {
  targetAllFill,
  indexExaminAllDataList //查询指标
} from "@/api/dailyExamine/targetExamine/indicatorFormulation";
import FormulateDialog from "./formulateDialog2"; //数据提供部门选择组件
import { validatenull } from "@/util/validate"; //判断空
import { remote as remoteDict } from "@/api/admin/dict"; //数据获取方式接口


export default {
  data() {
      var checkName = (rule, value, callback) => {
          if (value) {
              if (value.length>200) {
                  callback(new Error("最多可输入200字符!"));
              } else {
                  callback();
              }
          } else {
              callback(new Error("请输入考核名称"));
          }
      };
    var validateIDs = (rule, value, callback) => {
      if (this.options.length === 0) {
        callback(new Error("请选择被考核人"));
      } else {
        zltest(
          Object.assign(
            {
              assessId: this.fatherData.id, //考核周期id
              type: 0, //考核对象类型，0人员，1机构
              participantIds: this.getUserIds(this.options) //this.getUserIds(this.options)// 637//536//考核对象(人员或机构id) this.getUserIds(this.options)
            },
            ""
          )
        )
          .then(r => {
            if (r.msg) {
              callback(new Error("同一周期内被考核人不可以重复"));
            } else {
              callback();
            }
          })
          .catch(err => {});
      }
    };
    return {
      searchForm: {}, //查询对象
      pageData: {
        //分页对象
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0
      },
      isEdit: true, //是否编辑
      formulateDialog: false, //数据提供部门/人组件显隐
      canDelete: true, //是否能删除指标
      chooseTarget: [], //选中的指标
      repeatTargetList: [], //复用指标数组
      repeatList: [], //被选中的复用指标
      repeatVisible: false, //复用指标弹窗
      fatherData: {}, //新增时总部启动的考核数据
      dialogVisible: false, //考核指标库显隐
      multipleSelection: [], //选中的指标
      dataList: [], //指标数组
      oldDataList:[],//原始表格数据
      usercomment: false, //人员组件显隐
      options: [], //被考核人的数组
      dialogTitle: "新增人员考核", //弹窗标题
      visible: false, //最外层弹窗显隐
      dataForm: {
        //数据表单
        ids: []
      },
      formRules: {
        //校验规则
        name: [{ validator: checkName, trigger: "blur" }],
        ids: [{ validator: validateIDs, trigger: "blur" }],

      },
      // rules:{
      //   weight: [
      //       { required: true,message: "请输入数字", trigger: "blur" },
      //       {type:"number",message:"权重必须为数字值"}],
      // },
      submitForm: {
        //要提交给后台的数据对象
        name: null, //考核名称
        participantList: [], //被考核人
        kpiDetailList: [], //指标
        type: 0 //类型 0是人员 1 是机构
      },
      chooseDeptData: {}, //设置数据提供人的时候当前数据对象
      //news 2022/4/8
      templateNamesList: [],
      dataFromList:[],//数据获取方式列表

      post_flag:true,

    };
  },
  components: {
    UserCommonSelect,
    zhibiaoTable,
    FormulateDialog
  },
  watch: {
    // 监听指标选中变化
    multipleSelection: {
      handler(val) {
        if (val.length !== 0) {
          this.canDelete = false;
        } else {
          this.canDelete = true;
        }
      },
      deep: true
    },
    //监听被考核人变化，去掉提示
    options: {
      handler(val) {
        // 监听放在这个回调里面，不然会报错
        this.$nextTick(() => {
          this.$refs["dataForm"].clearValidate();
        });
      },
      deep: true
    }
  },
  methods: {
    // 全选
    onSelectAll(rows) {
      this.$refs.multipleTable.clearSelection();
    },
    checkIsNum(row,index){
        const szValid = /^[0-9]*$/
        if (!szValid.test(row.weight)) {
            this.$message.warning("分数设置请输入数字");
            return;
        }
    },
    tableRowClassName({row, rowIndex}) {
        if(!row.xyzb){
            return 'rowstyle';
        }

    },
    // 添加复用指标
    addRepeatIndex() {
      indexExaminAllDataList(this.repeatList[0].id)
        .then(r => {
          if (r.data.code == 0) {
              let tempList = r.data.data ;
              //筛选出重复指标，并做提示
              let normNameList = [] ;
              for(let i = 0; i < tempList.length; i++) {
                  let tempArr1 = tempList[i]
                  for(let j = 0; j < this.dataList.length; j++) {
                      let tempArr2 = this.dataList[j]
                      if(parseInt(tempArr2.normId) === parseInt(tempArr1.normId)){
                          normNameList.push(tempArr1.normName || tempArr1.name );
                      }
                  }
              }
              if (normNameList.length>0){
                  this.$message.error("“"+normNameList.toString()+"”不可重复添加") ;
              }

              const arr = [...this.dataList, ...Object.assign(tempList)]; //父子数据合并
              const newArr = arr.reduce(function (tempArr, item) { //去重
                  if (tempArr.findIndex((ele) => parseInt(ele.normId) === parseInt(item.normId)) === -1) {
                      tempArr.push(item)
                  }
                  return tempArr
              }, []);
              this.dataList = newArr ; //去重后的数据

            this.repeatVisible = false;
            this.dataList.map((it, index) => {
              it.renderIndex = index + 1;
              return it;
            });
          } else {
            this.repeatVisible = false;
          }
        })
        .catch(err => {
          this.repeatVisible = false;
        });
    },
    // 搜索复用指标
    handleSearch() {
      this.pageData.pageIndex = 1;
      this.getDataList();
    },
    // 查询复用指标列表
    getDataList() {
      examineList(
        Object.assign(
          {
            current: this.pageData.pageIndex,
            size: this.pageData.pageSize,
            type: 0
          },
          this.searchForm
        ),
        14
      )
        .then(r => {
          if (r.data.code == 0) {
              console.log(r)
            this.repeatTargetList = r.data.data.records;
            this.pageData.totalPage = r.data.data.total;
          }
        })
        .catch(err => {});
    },
    // 条数变化
    sizeChangeHandle(val) {
      this.pageData.pageSize = val;
      this.getDataList();
    },
    // 页码分页变化
    currentChangeHandle(val) {
      this.pageData.pageIndex = val;
      this.getDataList();
    },
    // 删除指标
    deleteIndex() {
      let tempArr = [];
      this.dataList = this.dataList.filter(itt => {
        let tem = this.multipleSelection.filter(it => {
          return itt.renderIndex == it.renderIndex;
        });
        return tem.length == 0;
      });
    },
    //news 2022/4/8 获取模板列表
    getTemplateName() {
      getMbnameSelect().then(r => {
        //let list=[];

        r.data.data.forEach(ele => {
          let item = {
            name: ele.templateName,
            value: ele.id
          };
          this.templateNamesList.push(item);
          if (ele.isZmb == 1) {
            this.dataForm.templateId = ele.id;
          }
        });
        //this.templateNamesList = list;
      });
    },
    //获取模板列表
    getXgTemplateName(templateId){
        getMbnameSelect().then(r => {
            //let list=[];

            r.data.data.forEach((ele) => {
                let item = {
                    name:ele.templateName,
                    value:ele.id
                }
                this.dataForm.templateId = templateId;
                this.templateNamesList.push(item);

            });

        });
    },
    //数据获取方式列表
    getNormDataTypes(){
        remoteDict("sys_norm_sjhqfs").then(response => {
            this.dataFromList = response.data.data;
        });
    },
    selecteRefresh() {
      this.$forceUpdate();
    },
    //筛选出姓名与职务
    shaiXuan(data, type) {
      var list = [],
        obj = {};
      if (type == "被考核人") {
        for (var i in data) {
          list.push(data[i].userName);
        }
      }
      return list.toString();
    },
    // 展示数据提供部门
    showDataProvide(data, index) {
      this.chooseDeptData = data;
      this.formulateDialog = true;
      this.jsonData = JSON.stringify([{}]);
      this.providerIndex = index;
      this.$nextTick(() => {
        this.$refs.formulateDialog.init("12", "ndts", this.jsonData, "ndcj");
      });
    },
    // 选中要复用的指标
    handleRepeatChange(rows) {
      if (rows.length > 1) {
        this.$refs.multipleTable.clearSelection();
        this.$refs.multipleTable.toggleRowSelection(rows.pop());
      } else {
        this.repeatList = rows;
      }
    },
    // 复用指标
    repeatTarget() {
      this.repeatVisible = true;
      this.getDataList();
    },
    // 添加指标
    addZhibiao() {
      let tempList = this.chooseTarget.map((it, index) => {
        it.type = it.normLx;
        it.name = it.normName;
        it.formula = it.normGsname;
        it.formulaId = it.normGs;
        it.completeValue = '手动获取'; //it.normGetDate;
        it.keiExplain = it.normSm;
        it.unit = it.normDw;
        it.itemIndex = it.normPx;
        it.normId = it.normId ;
        it.xyzb = true;
        return it;
      });

       //筛选出重复指标，并做提示
      let normNameList = [] ;
      for(let i = 0; i < tempList.length; i++) {
          let tempArr1 = tempList[i]
          for(let j = 0; j < this.dataList.length; j++) {
              let tempArr2 = this.dataList[j]
              if(parseInt(tempArr2.normId) === parseInt(tempArr1.normId)){
                  normNameList.push(tempArr1.normName);
                  break;
              }
          }
      }
      if (normNameList.length>0){
          this.$message.error("“"+normNameList.toString()+"”不可重复添加") ;
      }

      //this.dataList = [...this.dataList, ...Object.assign(tempList)];
      const arr = [...this.dataList, ...Object.assign(tempList)]; //父子数据合并
      const newArr = arr.reduce(function (tempArr, item) { //去重
          if (tempArr.findIndex((ele) => parseInt(ele.normId) === parseInt(item.normId)) === -1) {
              tempArr.push(item)
          }
          return tempArr
      }, []);
      this.dataList = newArr ; //去重后的数据

      this.dialogVisible = false;
      this.dataList.map((it, index) => {
        it.renderIndex = index + 1;
      });
     // console.log(this.dataList);
    },
    // 子组件穿过来的数据
    getRow(rows) {
      this.chooseTarget = rows;
    },
    // 显示指标表格
    showTarLibrary() {
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.zhibiaoRef.init(1, 1);
      });
    },
    // 选中指标
    handleSelectionChange(rows) {
      this.multipleSelection = rows;
    },
    // 被考核人改变
    personSelectChange(data) {
      this.participantList = [];
      this.options.map(it => {
        this.participantList.push({
          assessDeptId: it.deptId,
          assessDeptName: it.deptName,
          assessRealName: it.userName,
          assessUserId: it.userId,
          assessUserName: it.userCode
        });
      });
    },
    //   人员展示
    showPerson() {
      this.usercomment = true;
      this.$nextTick(() => {
        this.$refs.usercomment.init(
          "12",
          "sy",
          JSON.stringify(this.options),
          "htcj",
          "新增",
          undefined
        );
      });
    },
    // 选择人后的提交
    submitfy(data) {
      if (data.type == "shr") {
        this.dataList.map(it => {
          if (it.normId == this.chooseDeptData.normId) {
            this.$set(it, "provideRealName", data.tableDataUser[0].userName);
            this.$set(it, "provideUserName", data.tableDataUser[0].userCode);
            this.$set(it, "provideUserId", data.tableDataUser[0].userId);
            this.$set(it, "provideDeptName", data.tableDataUser[0].deptName);
            this.$set(it, "provideDeptId", data.tableDataUser[0].deptId);
          }
        });
      } else {
        this.options = data.tableDataUser;
        this.personSelectChange();
      }
    },

    getUserIds(userArr) {
      let ids = [];
      userArr.map(it => {
        ids.push(it.userId);
      });
      return ids.toString();
    },
    // 数据提供部门选择后的确定
    submitfy1(data) {
      if (this.dialogTitle == "编辑") {
        if (data.selectorgdata.length == 0) {
          this.dataList.map(it => {
            if (it.renderIndex == this.chooseDeptData.renderIndex) {
              this.$set(it, "provideRealName", data.tableDataUser[0].ryName);
              this.$set(it, "provideUserName", data.tableDataUser[0].userCode);
              this.$set(it, "provideUserId", data.tableDataUser[0].userId);
              this.$set(it, "provideDeptName", data.tableDataUser[0].deptName);
              this.$set(it, "provideDeptId", data.tableDataUser[0].deptId);
              this.$set(it, "isLiaison", 0);
            }
          });
        } else {
          this.dataList.map(it => {
            if (it.renderIndex == this.chooseDeptData.renderIndex) {
              this.$set(it, "provideRealName", data.selectorgdata[0].ryName);
              this.$set(it, "provideUserName", data.selectorgdata[0].userCode);
              this.$set(it, "provideUserId", data.selectorgdata[0].userId);
              this.$set(it, "provideDeptName", data.selectorgdata[0].deptName);
              this.$set(it, "provideDeptId", data.selectorgdata[0].deptId);
              this.$set(it, "isLiaison", 1);
            }
          });
        }
      } else {
        if (data.selectorgdata.length == 0) {
          this.dataList.map(it => {
            if (it.normId == this.chooseDeptData.normId) {
              this.$set(it, "provideRealName", data.tableDataUser[0].ryName);
              this.$set(it, "provideUserName", data.tableDataUser[0].userCode);
              this.$set(it, "provideUserId", data.tableDataUser[0].userId);
              this.$set(it, "provideDeptName", data.tableDataUser[0].deptName);
              this.$set(it, "provideDeptId", data.tableDataUser[0].deptId);
              this.$set(it, "isLiaison", 0);
            }
          });
        } else {
          this.dataList.map(it => {
            if (it.normId == this.chooseDeptData.normId) {
              this.$set(it, "provideRealName", data.selectorgdata[0].ryName);
              this.$set(it, "provideUserName", data.selectorgdata[0].userCode);
              this.$set(it, "provideUserId", data.selectorgdata[0].userId);
              this.$set(it, "provideDeptName", data.selectorgdata[0].deptName);
              this.$set(it, "provideDeptId", data.selectorgdata[0].deptId);
              this.$set(it, "isLiaison", 1);
            }
          });
        }
      }
    },
    // 确定新增
    handleConfirm() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.submitForm.kpiDetailList = this.dataList.map(it => {
            delete it.createDeptId;
            delete it.createDeptName;
            delete it.createTime;
            delete it.createUserId;
            delete it.createUserName;
            delete it.dataState;
            delete it.editDeptId;
            delete it.editDeptName;
            delete it.editTime;
            delete it.editUserId;
            delete it.editUserName;
            delete it.tenantId;
            delete it.id;
            it.assessId = this.fatherData.id;
            return it;
          });

          //验证指标列表中数据提供部门/人不可为空
          let flag = this.submitForm.kpiDetailList.every( it=> {
           return !validatenull(it.isLiaison) && ( (it.isLiaison==0 && !validatenull(it.provideRealName))||(it.isLiaison==1 && !validatenull(it.provideDeptName)))
          }) ;
          if(!flag){
              this.$message.error('数据提供部门/人不可空');
              return ;
          }
          const szValid = /^[0-9]*$/;
          let flagWeight = this.submitForm.kpiDetailList.every( it=> {
              return !validatenull(it.weight)
          }) ;
          if(!flagWeight){
              this.$message.error('权重不可为空');
              return ;
          }

          //验证是否超200字
          let flagTargetValue = this.submitForm.kpiDetailList.every( it=> {
               return validatenull(it.targetValue) || (!validatenull(it.targetValue) && it.targetValue.length<=200) ;
          }) ;
          if (!flagTargetValue){
              this.$message.error('目标值不可超过200字');
              return ;
          }

          this.submitForm.name = this.dataForm.name;
          this.submitForm.assessId = this.fatherData.id;
          this.submitForm.period = this.fatherData.period;
          this.submitForm.assessBeginTime = this.fatherData.assessBeginTime;
          this.submitForm.assessEndTime = this.fatherData.assessEndTime;
          this.submitForm.completeBeginTime = this.fatherData.completeBeginTime;
          this.submitForm.completeEndTime = this.fatherData.completeEndTime;
          //news 2022/4/8
          this.submitForm.templateId = this.dataForm.templateId;
          if(!this.post_flag) {
              this.$message.error("请不要重复提交，请求正在处理中");
              return; //如果正在提交则直接返回，停止执行
          }
          this.post_flag = false;//标记当前状态为正在提交状态

          if (this.dialogTitle == "编辑") {
            delete this.submitForm.participantList;
            this.submitForm.participantId = this.dataForm.id;
            this.submitForm.assessId = this.dataForm.assessId;

              //原数据和新添加的数据对比，返回非重复值
              const res= this.dataList.filter((e)=>!this.oldDataList.some((e2)=>parseInt(e2.normId)===parseInt(e.normId)))
              let normIds = res.map(it=>{
                  return parseInt(it.normId) ;
              })

              if (normIds.length == 0){ //不做验证
                  editExamin(this.submitForm)
                      .then(r => {
                          if (r.data.code == 0) {
                              this.post_flag = true; //在提交成功之后将标志标记为可提交状态
                              this.$message.success("编辑成功");
                              this.$emit("closeDialog");
                              this.$emit("refesData");
                          }
                      })
                      .catch(err => {
                          this.post_flag = true; //在提交成功之后将标志标记为可提交状态
                          this.$message.error(r.data.msg);
                          this.$emit("closeDialog");
                          this.$emit("refesData");
                      });
               }else{
                  checkitem(this.fatherData.id, normIds.toString()) //验证新增的指标是否有重复
                      .then(r => {
                          if (!r.data.msg) {
                              editExamin(this.submitForm)
                                  .then(r => {
                                      if (r.data.code == 0) {
                                          this.post_flag = true; //在提交成功之后将标志标记为可提交状态
                                          this.$message.success("编辑成功");
                                          this.$emit("closeDialog");
                                          this.$emit("refesData");
                                      }
                                  })
                                  .catch(err => {
                                      this.post_flag = true; //在提交成功之后将标志标记为可提交状态
                                      this.$message.error(r.data.msg);
                                      this.$emit("closeDialog");
                                      this.$emit("refesData");
                                  });
                          }else{
                              this.post_flag = true; //在提交成功之后将标志标记为可提交状态
                              this.$message.error(r.data.msg) ;
                          }
                  })
              }

          } else {
            this.submitForm.participantList = this.participantList;

            if(this.submitForm.templateId == "" || this.submitForm.templateId == null ){
                this.$message.error("模板名称不能为空！");
                return false;
            }
            addExamin(this.submitForm)
              .then(r => {
                if (r.data.code == 0) {
                  this.post_flag = true; //在提交成功之后将标志标记为可提交状态
                  this.$message.success("新增成功");
                  this.$emit("closeDialog");
                  this.$emit("refesData");
                }
              })
              .catch(err => {
                this.post_flag = true; //在提交成功之后将标志标记为可提交状态
                this.$message.error(r.data.msg);
                this.$emit("closeDialog");
                this.$emit("refesData");
              });
          }
        } else {
          this.post_flag = true; //在提交成功之后将标志标记为可提交状态
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 初始化
    init(data, editData, type) {
      this.visible = true;
      this.fatherData = data.data;
      if (type == "edit") {
        this.isEdit = true;
        this.getXgTemplateName(editData.templateId);//模板
        this.fatherData.period = editData.period;
      } else {
        this.isEdit = false;
        this.getTemplateName(); //模板
      }

      this.getNormDataTypes() ; //数据获取方式列表
      if (editData) {
        if (editData) {
          this.dialogTitle = "编辑";
          this.dataForm = editData;
          this.options.push({
            deptId: editData.assessDeptId,
            deptName: editData.assessDeptName,
            userName: editData.assessRealName,
            userId: editData.assessUserId,
            userCode: editData.assessUserName
          });
          indexExaminAllDataList(editData.id)
            .then(r => {
              if (r.data.code == 0) {
                  console.log(r)
                this.dataList = r.data.data.map((it, index) => {
                  it.renderIndex = index + 1;
                  return it;
                });
                this.oldDataList = this.dataList ; //保留一份原始数据
                this.personSelectChange();
              }
            })
            .catch(err => {});
        }
      }
    },
    // 表单提交
    dataFormSubmit() {},
    // 关闭
    closeDialog() {
      this.visible = false;
      this.$emit("closeDialog");
    }
  }
};
</script>

<style lang="scss" scoped>
/deep/ .el-table__body tr.rowstyle >td {
    background-color: #f0c9cb;
  }
.tabBox {
  width: 100%;
  .btnBox {
    display: flex;
    justify-content: space-between;
  }
}
.weightRed {
  color: rgba(255, 0, 0, 0.726);
}

</style>
